#include "foodselect.h"
#include "ui_foodselect.h"
#include <QToolButton>
#include <QLineEdit>
#include <QList>
#include "food.h"
#include "fooditem.h"
#include <QDebug>
#include <QScroller>
FoodSelect::FoodSelect(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FoodSelect)
{
    ui->setupUi(this);
    connect(ui->listWidget,&MyListWidget::reachedBottom,this,[=](){
        QList<Food> result = sql.foodSearch(ui->keyword->text(),size,++index);
        qDebug()<<result;
        for(int i = 0 ; i<result.size();i++)
        {
            QListWidgetItem *optItem = new QListWidgetItem(ui->listWidget);
            FoodItem* fooditem = new FoodItem(this);
            fooditemlist.append(fooditem);
            fooditem->update(result.at(i));
            ui->listWidget->addItem(optItem);
            ui->listWidget->setItemWidget(optItem,fooditem);
            optItem->setSizeHint(fooditem->size());
            optItem->setFlags(Qt::NoItemFlags);
            connect(fooditem,&FoodItem::selected,this,[=](Food food){
                emit selected(food);
            });
        }
    });
    ui->listWidget->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
    ui->listWidget->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
    QScroller::grabGesture(ui->listWidget,QScroller::LeftMouseButtonGesture);
    connect(ui->search,&QToolButton::clicked,this,[=](){
        qDebug()<<"点击了食物搜索";
        index = 1;
        int n=ui->listWidget->count();//获取item的总数
        //删去所有item
        for(int i=0;i<n;i++)
        {
            /*
             使用takeItem(row)函数将QListWidget中的第row个item移除，
             移除需要使用delete手动释放其在堆上占用的空间
            */
            //这里是0，不是i，因为每移除一个item都会导致每个item的row发生变化
            QListWidgetItem *item = ui->listWidget->takeItem(0);
            delete item;
        }
        n = this->fooditemlist.size();
        for(int i=0;i<n;i++)
        {
            fooditemlist.at(0)->close();
            fooditemlist.at(0)->deleteLater();
            fooditemlist.removeAt(0);
        }
        ui->listWidget->clear();
        QList<Food> result = sql.foodSearch(ui->keyword->text(),size,index);
        qDebug()<<result;
        for(int i = 0 ; i<result.size();i++)
        {
            FoodItem* fooditem = new FoodItem(this);
            fooditem->update(result.at(i));
            QListWidgetItem *optItem = new QListWidgetItem();
            ui->listWidget->addItem(optItem);
            ui->listWidget->setItemWidget(optItem,fooditem);
            optItem->setSizeHint(fooditem->size());
            optItem->setFlags(Qt::NoItemFlags);
            connect(fooditem,&FoodItem::selected,this,[=](Food food){
                emit selected(food);
            });
        }

    });

//    connect(ui->showKeyboard,&QToolButton::clicked,[=](){
//        emit ui->keyword->clicked();
//    });

}

FoodSelect::~FoodSelect()
{
    delete ui;
}
